<template>
  <div class="ai-container">
    <div class="page-header">
      <h1 class="page-title">AI分析数据</h1>
      <p class="page-description">查看和管理AI面部分析结果数据</p>
    </div>

    <div class="content-area">
      <!-- 统计卡片 -->
      <div class="stats-section">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-card class="stats-card">
              <div class="stats-content">
                <div class="stats-number">{{ statistics.totalAnalysis }}</div>
                <div class="stats-label">总分析次数</div>
              </div>
              <el-icon class="stats-icon" color="#409EFF"
                ><DataAnalysis
              /></el-icon>
            </el-card>
          </el-col>
          <el-col :span="6">
            <el-card class="stats-card">
              <div class="stats-content">
                <div class="stats-number">{{ statistics.todayAnalysis }}</div>
                <div class="stats-label">今日分析</div>
              </div>
              <el-icon class="stats-icon" color="#67C23A"
                ><TrendCharts
              /></el-icon>
            </el-card>
          </el-col>
          <el-col :span="6">
            <el-card class="stats-card">
              <div class="stats-content">
                <div class="stats-number">{{ statistics.avgScore }}</div>
                <div class="stats-label">平均得分</div>
              </div>
              <el-icon class="stats-icon" color="#E6A23C"><Star /></el-icon>
            </el-card>
          </el-col>
          <el-col :span="6">
            <el-card class="stats-card">
              <div class="stats-content">
                <div class="stats-number">{{ statistics.successRate }}%</div>
                <div class="stats-label">成功率</div>
              </div>
              <el-icon class="stats-icon" color="#F56C6C"
                ><SuccessFilled
              /></el-icon>
            </el-card>
          </el-col>
        </el-row>
      </div>

      <!-- 搜索区域 -->
      <div class="search-section">
        <el-form :model="searchForm" inline>
          <el-form-item label="分析时间">
            <el-date-picker
              v-model="searchForm.dateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
            />
          </el-form-item>
          <el-form-item label="性别">
            <el-select
              v-model="searchForm.gender"
              placeholder="请选择性别"
              clearable
              style="width: 120px"
            >
              <el-option label="男性" value="male" />
              <el-option label="女性" value="female" />
            </el-select>
          </el-form-item>
          <el-form-item label="年龄段">
            <el-select
              v-model="searchForm.ageRange"
              placeholder="请选择年龄段"
              clearable
              style="width: 160px"
            >
              <el-option label="未成年 (0-17岁)" value="0-17" />
              <el-option label="青年 (18-24岁)" value="18-24" />
              <el-option label="成年早期 (25-34岁)" value="25-34" />
              <el-option label="成年中期 (35-44岁)" value="35-44" />
              <el-option label="成年后期 (45-54岁)" value="45-54" />
              <el-option label="中老年 (55-64岁)" value="55-64" />
              <el-option label="老年 (65-74岁)" value="65-74" />
              <el-option label="高龄 (75岁以上)" value="75+" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">搜索</el-button>
            <el-button @click="handleReset">重置</el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 操作按钮区域 -->
      <div class="action-section">
        <div class="action-buttons">
          <el-button type="primary" @click="handleRefresh">
            <el-icon><Refresh /></el-icon>
            刷新数据
          </el-button>
          <el-dropdown @command="handleExportCommand">
            <el-button type="success">
              <el-icon><Download /></el-icon>
              导出报告 <el-icon class="el-icon--right"><ArrowDown /></el-icon>
            </el-button>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item command="with-images"
                  >导出报告（含图片）</el-dropdown-item
                >
                <el-dropdown-item command="paths-only"
                  >导出报告（仅路径）</el-dropdown-item
                >
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>
      </div>

      <!-- 数据表格 -->
      <div class="table-section" ref="tableContainer">
        <el-table
          :data="tableData"
          :loading="loading"
          border
          stripe
          :height="tableHeight"
          ref="tableRef"
          @scroll="handleTableDirectScroll"
        >
          <el-table-column prop="id" label="分析ID" width="100" />
          <el-table-column label="用户图片" width="100">
            <template #default="scope">
              <div class="image-container">
                <el-image
                  v-if="scope.row.imageUrl"
                  :src="scope.row.imageUrl"
                  :preview-src-list="[scope.row.imageUrl]"
                  class="table-image"
                  fit="cover"
                  :preview-teleported="true"
                  :z-index="3000"
                  lazy
                  :scroll-container="lazyScrollContainer"
                  loading="lazy"
                >
                  <template #placeholder>
                    <div class="image-placeholder">
                      <el-icon class="is-loading"><Loading /></el-icon>
                      <span>加载中...</span>
                    </div>
                  </template>
                  <template #error>
                    <div class="image-error">
                      <el-icon><Picture /></el-icon>
                      <span>加载失败</span>
                    </div>
                  </template>
                </el-image>
                <div v-else class="no-image">
                  <el-icon><Picture /></el-icon>
                  <span>暂无图片</span>
                </div>
              </div>
            </template>
          </el-table-column>
          <el-table-column
            prop="faceCount"
            label="检测人脸数"
            width="120"
            align="center"
          />
          <el-table-column
            prop="gender"
            label="性别"
            width="80"
            align="center"
          />
          <el-table-column prop="age" label="年龄" width="80" align="center" />
          <el-table-column
            prop="goldenRatioScore"
            label="黄金比例得分"
            width="300"
            align="center"
          >
            <template #default="scope">
              <el-progress
                :percentage="scope.row.goldenRatioScore"
                :color="getScoreColor(scope.row.goldenRatioScore)"
                :show-text="true"
              />
            </template>
          </el-table-column>
          <el-table-column
            prop="mainEmotion"
            label="主要表情"
            width="100"
            align="center"
          />
          <el-table-column
            prop="faceShape"
            label="脸型"
            width="100"
            align="center"
          />
          <el-table-column prop="analysisTime" label="分析时间" width="160" />
          <el-table-column label="操作" width="300" fixed="right">
            <template #default="scope">
              <el-button size="small" @click="handleView(scope.row)"
                >查看详情</el-button
              >
              <el-dropdown
                @command="(cmd) => handleDownloadReport(cmd, scope.row)"
                size="small"
              >
                <el-button size="small" type="success">
                  <el-icon><Download /></el-icon>
                  下载报告
                  <el-icon class="el-icon--right"><ArrowDown /></el-icon>
                </el-button>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item command="image"
                      >下载图片报告</el-dropdown-item
                    >
                    <el-dropdown-item command="text"
                      >下载文本报告</el-dropdown-item
                    >
                    <el-dropdown-item command="simple-image"
                      >下载简化图片</el-dropdown-item
                    >
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </template>
          </el-table-column>
        </el-table>

        <!-- 滚动触发器 - 用于检测是否触底 -->
        <div
          ref="scrollTrigger"
          class="scroll-trigger"
          style="height: 1px; margin-top: -1px"
        ></div>
      </div>
    </div>

    <!-- 详情对话框 -->
    <el-dialog
      v-model="detailVisible"
      title="AI分析详情"
      width="85%"
      top="2vh"
      :close-on-click-modal="false"
      :close-on-press-escape="true"
      class="detail-dialog"
    >
      <div v-if="currentDetail" class="detail-content">
        <!-- 头部信息卡片 -->
        <div class="detail-header">
          <el-card shadow="never" class="header-card">
            <div class="header-info">
              <div class="header-left">
                <div class="user-avatar">
                  <el-image
                    v-if="currentDetail.imageUrl"
                    :src="currentDetail.imageUrl"
                    class="avatar-image"
                    fit="cover"
                  >
                    <template #error>
                      <div class="avatar-error">
                        <el-icon><Picture /></el-icon>
                      </div>
                    </template>
                  </el-image>
                  <div v-else class="avatar-placeholder">
                    <el-icon><Picture /></el-icon>
                  </div>
                </div>
              </div>
              <div class="header-right">
                <h2 class="analysis-title">
                  分析报告 #{{ currentDetail.id.slice(-6) }}
                </h2>
                <div class="basic-tags">
                  <el-tag type="primary" size="large">{{
                    currentDetail.gender
                  }}</el-tag>
                  <el-tag type="success" size="large"
                    >{{ currentDetail.age }}岁</el-tag
                  >
                  <el-tag type="info" size="large">{{
                    currentDetail.faceShape
                  }}</el-tag>
                  <el-tag type="warning" size="large">{{
                    currentDetail.mainEmotion
                  }}</el-tag>
                </div>
                <div class="score-display">
                  <span class="score-label">黄金比例得分</span>
                  <div class="score-progress">
                    <el-progress
                      :percentage="currentDetail.goldenRatioScore"
                      :color="getScoreColor(currentDetail.goldenRatioScore)"
                      :stroke-width="12"
                      :show-text="true"
                    />
                  </div>
                </div>
              </div>
            </div>
          </el-card>
        </div>

        <!-- 详细信息区域 -->
        <el-row :gutter="0" class="detail-body">
          <el-col :span="12">
            <el-card shadow="hover" class="info-card">
              <template #header>
                <div class="card-header">
                  <el-icon class="header-icon"><DataAnalysis /></el-icon>
                  <span>基本信息</span>
                </div>
              </template>
              <el-descriptions :column="1" size="large">
                <el-descriptions-item
                  label="分析ID"
                  label-class-name="desc-label"
                >
                  <el-text type="primary">{{ currentDetail.id }}</el-text>
                </el-descriptions-item>
                <el-descriptions-item
                  label="检测人脸数"
                  label-class-name="desc-label"
                >
                  <el-text>{{ currentDetail.faceCount }} 个</el-text>
                </el-descriptions-item>
                <el-descriptions-item
                  label="分析时间"
                  label-class-name="desc-label"
                >
                  <el-text type="info">{{
                    currentDetail.analysisTime || "未知"
                  }}</el-text>
                </el-descriptions-item>
              </el-descriptions>
            </el-card>
          </el-col>

          <el-col :span="12">
            <el-card shadow="hover" class="info-card">
              <template #header>
                <div class="card-header">
                  <el-icon class="header-icon"><TrendCharts /></el-icon>
                  <span>分析结果</span>
                </div>
              </template>
              <div class="analysis-content">
                <div class="score-detail">
                  <div class="score-number">
                    {{ currentDetail.goldenRatioScore }}%
                  </div>
                  <div class="score-desc">黄金比例匹配度</div>
                </div>
                <el-divider />
                <div class="features-list">
                  <div class="feature-item">
                    <span class="feature-label">面部特征：</span>
                    <span class="feature-value">{{
                      currentDetail.faceShape
                    }}</span>
                  </div>
                  <div class="feature-item">
                    <span class="feature-label">表情状态：</span>
                    <span class="feature-value">{{
                      currentDetail.mainEmotion
                    }}</span>
                  </div>
                </div>
              </div>
            </el-card>
          </el-col>
        </el-row>

        <!-- AI分析内容 -->
        <div v-if="currentDetail.aiAnalysis" class="detail-section">
          <el-card shadow="hover" class="analysis-card">
            <template #header>
              <div class="card-header">
                <el-icon class="header-icon"><Star /></el-icon>
                <span>AI智能分析</span>
              </div>
            </template>
            <div class="ai-analysis-content">
              <el-scrollbar height="600px">
                <div
                  class="analysis-text"
                  v-html="formatAnalysisText(currentDetail.aiAnalysis)"
                ></div>
              </el-scrollbar>
            </div>
          </el-card>
        </div>
      </div>
    </el-dialog>

    <!-- 隐藏的图片报告模板 -->
    <div
      ref="imageReportTemplate"
      class="image-report-template"
      v-show="false"
      style="
        position: absolute;
        top: -9999px;
        left: -9999px;
        background: white;
        padding: 40px;
        width: 800px;
        font-family: 'Microsoft YaHei', sans-serif;
      "
    >
      <div v-if="reportData" class="report-container">
        <!-- 报告头部 -->
        <div
          class="report-header"
          style="
            text-align: center;
            margin-bottom: 30px;
            border-bottom: 3px solid #409eff;
            padding-bottom: 20px;
          "
        >
          <h1
            style="
              color: #409eff;
              margin: 0;
              font-size: 28px;
              font-weight: bold;
            "
          >
            AI面部分析报告
          </h1>
          <p style="color: #666; margin: 10px 0 0 0; font-size: 16px">
            专业面部特征分析与评估
          </p>
        </div>

        <!-- 用户信息和照片 -->
        <div
          class="report-content"
          style="display: flex; gap: 30px; margin-bottom: 30px"
        >
          <!-- 左侧照片 -->
          <div class="user-image-section" style="flex: 0 0 200px">
            <div style="text-align: center">
              <div
                style="
                  width: 200px;
                  height: 200px;
                  border-radius: 10px;
                  overflow: hidden;
                  border: 3px solid #e6f3ff;
                  margin-bottom: 15px;
                "
              >
                <img
                  v-if="reportData.imageUrl"
                  :src="getProxiedImageUrl(reportData.imageUrl)"
                  style="width: 100%; height: 100%; object-fit: cover"
                  crossorigin="anonymous"
                  @error="handleImageError"
                />
                <div
                  v-else
                  style="
                    width: 100%;
                    height: 100%;
                    background: #f5f5f5;
                    display: flex;
                    align-items: center;
                    justify-content: center;
                    color: #999;
                    font-size: 14px;
                  "
                >
                  暂无照片
                </div>
              </div>
              <p style="margin: 0; color: #666; font-size: 14px">
                分析编号: {{ reportData.id.slice(-8) }}
              </p>
            </div>
          </div>

          <!-- 右侧基本信息 -->
          <div class="user-info-section" style="flex: 1">
            <div
              class="info-grid"
              style="
                display: grid;
                grid-template-columns: repeat(2, 1fr);
                gap: 20px;
                margin-bottom: 25px;
              "
            >
              <div
                class="info-item"
                style="
                  background: #f8f9fa;
                  padding: 15px;
                  border-radius: 8px;
                  border-left: 4px solid #67c23a;
                "
              >
                <div style="font-size: 12px; color: #666; margin-bottom: 5px">
                  性别
                </div>
                <div style="font-size: 18px; font-weight: bold; color: #67c23a">
                  {{ reportData.gender }}
                </div>
              </div>
              <div
                class="info-item"
                style="
                  background: #f8f9fa;
                  padding: 15px;
                  border-radius: 8px;
                  border-left: 4px solid #e6a23c;
                "
              >
                <div style="font-size: 12px; color: #666; margin-bottom: 5px">
                  年龄
                </div>
                <div style="font-size: 18px; font-weight: bold; color: #e6a23c">
                  {{ reportData.age }}岁
                </div>
              </div>
              <div
                class="info-item"
                style="
                  background: #f8f9fa;
                  padding: 15px;
                  border-radius: 8px;
                  border-left: 4px solid #409eff;
                "
              >
                <div style="font-size: 12px; color: #666; margin-bottom: 5px">
                  脸型
                </div>
                <div style="font-size: 18px; font-weight: bold; color: #409eff">
                  {{ reportData.faceShape }}
                </div>
              </div>
              <div
                class="info-item"
                style="
                  background: #f8f9fa;
                  padding: 15px;
                  border-radius: 8px;
                  border-left: 4px solid #f56c6c;
                "
              >
                <div style="font-size: 12px; color: #666; margin-bottom: 5px">
                  主要表情
                </div>
                <div style="font-size: 18px; font-weight: bold; color: #f56c6c">
                  {{ reportData.mainEmotion }}
                </div>
              </div>
            </div>

            <!-- 黄金比例得分 -->
            <div
              class="score-section"
              style="
                background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
                color: white;
                padding: 20px;
                border-radius: 10px;
                text-align: center;
              "
            >
              <div style="font-size: 14px; margin-bottom: 8px; opacity: 0.9">
                黄金比例匹配度
              </div>
              <div
                style="font-size: 36px; font-weight: bold; margin-bottom: 5px"
              >
                {{ reportData.goldenRatioScore }}%
              </div>
              <div style="font-size: 12px; opacity: 0.8">
                {{ getScoreLevel(reportData.goldenRatioScore) }}
              </div>
            </div>
          </div>
        </div>

        <!-- 分析详情 -->
        <div
          v-if="reportData.aiAnalysis"
          class="analysis-section"
          style="
            background: #f8f9fa;
            padding: 25px;
            border-radius: 10px;
            margin-bottom: 20px;
          "
        >
          <h3
            style="
              color: #409eff;
              margin: 0 0 20px 0;
              font-size: 20px;
              border-bottom: 2px solid #e6f3ff;
              padding-bottom: 10px;
            "
          >
            AI智能分析
          </h3>
          <div
            class="analysis-content"
            style="line-height: 1.8; color: #333; font-size: 14px"
            v-html="formatAnalysisForImage(reportData.aiAnalysis)"
          ></div>
        </div>

        <!-- 报告底部 -->
        <div
          class="report-footer"
          style="
            text-align: center;
            padding-top: 20px;
            border-top: 1px solid #e6e6e6;
            color: #999;
            font-size: 12px;
          "
        >
          <p style="margin: 0">
            生成时间: {{ new Date().toLocaleDateString() }}
            {{ new Date().toLocaleTimeString() }}
          </p>
          <p style="margin: 5px 0 0 0">报告由AI智能分析系统生成 | 仅供参考</p>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed, nextTick, onUnmounted } from "vue";
import { ElMessage } from "element-plus";
import {
  DataAnalysis,
  TrendCharts,
  Star,
  SuccessFilled,
  Refresh,
  Download,
  Picture,
  Loading,
  ArrowDown,
} from "@element-plus/icons-vue";

// 引入样式文件
import "./CSS/Ai.css";
// 引入Excel库和图片生成库
import * as XLSX from "xlsx";
import html2canvas from "html2canvas";

// 定义接口类型
interface AiAnalysis {
  id: string;
  imageUrl?: string;
  faceCount: number;
  gender: string;
  age: number;
  goldenRatioScore: number;
  mainEmotion: string;
  faceShape: string;
  analysisTime: string;
  aiAnalysis?: string;
}

// Excel列配置接口（本地定义）
interface ExcelColumn {
  key: string;
  title: string;
  width?: number;
  formatter?: (value: any, row: any) => string;
}

interface SearchForm {
  dateRange: string[];
  gender: string;
  ageRange: string;
}

interface Statistics {
  totalAnalysis: number;
  todayAnalysis: number;
  avgScore: number;
  successRate: number;
}

// 响应式数据
const loading = ref(false);
const tableData = ref<AiAnalysis[]>([]);
const detailVisible = ref(false);
const currentDetail = ref<AiAnalysis | null>(null);
const tableContainer = ref<HTMLElement>();
const tableRef = ref<any>(null);
const scrollTrigger = ref<HTMLElement>();
const tableHeight = ref(400);

// 图片报告相关
const imageReportTemplate = ref<HTMLElement>();
const reportData = ref<AiAnalysis | null>(null);

// Excel导出配置

// Excel列配置
const excelColumns: ExcelColumn[] = [
  { key: "id", title: "分析ID", width: 15 },
  {
    key: "imageUrl",
    title: "用户图片",
    width: 50,
    formatter: (value: string) => value || "暂无图片",
  },
  { key: "faceCount", title: "检测人脸数", width: 12 },
  { key: "gender", title: "性别", width: 10 },
  { key: "age", title: "年龄", width: 10 },
  {
    key: "goldenRatioScore",
    title: "黄金比例得分",
    width: 15,
    formatter: (value: number) => `${value}%`,
  },
  { key: "mainEmotion", title: "主要表情", width: 12 },
  { key: "faceShape", title: "脸型", width: 12 },
  { key: "analysisTime", title: "分析时间", width: 20 },
];

// 无限滚动相关
const loadingMore = ref(false); // 保留用于防止重复请求
const hasMoreData = ref(true);
const currentPage = ref(1);
const pageSize = ref(10);
const totalCount = ref(0);
let scrollCleanup: (() => void) | null = null;
let intersectionObserver: IntersectionObserver | null = null;
let loadingMessageInstance: any = null; // 用于控制加载中提示的实例
let lastTriggerTime = 0; // 用于防抖的时间戳

// 懒加载滚动容器
const lazyScrollContainer = computed(() => {
  return (
    tableRef.value?.$el?.querySelector(".el-table__body-wrapper") || undefined
  );
});

const searchForm = reactive<SearchForm>({
  dateRange: [],
  gender: "",
  ageRange: "",
});

const statistics = reactive<Statistics>({
  totalAnalysis: 0,
  todayAnalysis: 0,
  avgScore: 0,
  successRate: 0,
});

// 计算属性
const getScoreColor = computed(() => {
  return (score: number) => {
    if (score >= 85) return "#67c23a";
    if (score >= 70) return "#e6a23c";
    if (score >= 60) return "#f56c6c";
    return "#909399";
  };
});

// 计算表格高度
const calculateTableHeight = () => {
  nextTick(() => {
    try {
      // 获取容器元素
      const container = document.querySelector(".ai-container") as HTMLElement;
      if (!container) {
        console.warn("容器元素未找到，使用默认高度");
        tableHeight.value = 400;
        return;
      }

      // 获取各个区域的实际高度
      const pageHeader = container.querySelector(".page-header") as HTMLElement;
      const statsSection = container.querySelector(
        ".stats-section"
      ) as HTMLElement;
      const searchSection = container.querySelector(
        ".search-section"
      ) as HTMLElement;
      const actionSection = container.querySelector(
        ".action-section"
      ) as HTMLElement;

      // 计算已使用的高度
      let usedHeight = 0;
      if (pageHeader) usedHeight += pageHeader.offsetHeight + 20; // 包含margin
      if (statsSection) usedHeight += statsSection.offsetHeight + 24; // 包含margin
      if (searchSection) usedHeight += searchSection.offsetHeight + 20; // 包含margin
      if (actionSection) usedHeight += actionSection.offsetHeight + 20; // 包含margin

      // 容器内边距
      usedHeight += 40; // 容器上下padding各20px

      // 计算可用高度
      const containerHeight = container.offsetHeight;
      const availableHeight = containerHeight - usedHeight;

      // 设置表格高度，最小200px
      tableHeight.value = Math.max(200, availableHeight - 20); // 预留20px缓冲

      // console.log(`容器高度: ${containerHeight}px, 已用高度: ${usedHeight}px, 表格高度: ${tableHeight.value}px`)
    } catch (error) {
      console.error("计算表格高度时出错:", error);
      tableHeight.value = 400; // 默认高度
    }
  });
};

// 窗口大小改变监听
const handleResize = () => {
  calculateTableHeight();
};

// 搜索处理
const handleSearch = () => {
  resetPagination();
  fetchData().then(() => {
    // 重新设置滚动监听
    setTimeout(() => {
      setupTableScrollListener();
      setupIntersectionObserver();
    }, 100);
  });
};

// 重置搜索
const handleReset = () => {
  Object.assign(searchForm, {
    dateRange: [],
    gender: "",
    ageRange: "",
  });
  handleSearch();
};

// 重置分页状态
const resetPagination = () => {
  currentPage.value = 1;
  tableData.value = [];
  hasMoreData.value = true;
  totalCount.value = 0;
};

// 刷新数据
const handleRefresh = () => {
  resetPagination();
  fetchData().then(() => {
    // 重新设置滚动监听
    setTimeout(() => {
      setupTableScrollListener();
      setupIntersectionObserver();
    }, 100);
  });
  fetchStatistics();
};

// 处理导出命令选择
const handleExportCommand = async (command: any) => {
  if (tableData.value.length === 0) {
    ElMessage.warning("暂无数据可导出");
    return;
  }

  const filename = `AI分析数据_${new Date().toLocaleDateString()}`;
  const includeImages = command === "with-images";

  try {
    if (includeImages) {
      ElMessage.info("正在导出含图片的报告，请稍候...");
    }

    await exportToExcel(tableData.value, filename, includeImages);

    const message = includeImages
      ? "AI分析报告（含图片）导出成功！"
      : "AI分析报告（仅路径）导出成功！";
    ElMessage.success(message);
  } catch (error) {
    console.error("导出失败:", error);
    ElMessage.error("导出失败，请重试");
  }
};

// 兼容性：保留原有的导出方法（仅用于向后兼容）
// const handleExport = () => handleExportCommand('with-images');


// 查看详情
const handleView = (row: AiAnalysis) => {
  currentDetail.value = row;
  detailVisible.value = true;
};

// 处理单个报告下载命令选择（Excel导出，保留备用）
// const handleDownloadCommand = async (command: any, row: AiAnalysis) => {
//   const filename = `AI分析报告_${row.id}_${new Date().toLocaleDateString()}`;
//   const includeImages = command === "with-images";
//   try {
//     if (includeImages) {
//       ElMessage.info("正在导出含图片的单个报告，请稍候...");
//     }
//     const singleRowData = [row];
//     await exportToExcel(singleRowData, filename, includeImages);
//     const message = includeImages
//       ? `报告 ${row.id}（含图片）导出成功！`
//       : `报告 ${row.id}（仅路径）导出成功！`;
//     ElMessage.success(message);
//   } catch (error) {
//     console.error("单个报告导出失败:", error);
//     ElMessage.error("导出失败，请重试");
//   }
// };

// 下载图片报告
const handleDownloadImage = async (row: AiAnalysis) => {
  try {
    ElMessage.info("正在生成图片报告，请稍候...");

    // 设置报告数据
    reportData.value = row;

    // 等待DOM更新
    await nextTick();

    // 额外等待确保样式完全应用
    await new Promise((resolve) => setTimeout(resolve, 500));

    // 等待图片加载
    await waitForImages();

    // 生成图片
    if (imageReportTemplate.value) {
      // 临时显示元素以确保正确渲染
      const originalDisplay = imageReportTemplate.value.style.display;
      const originalPosition = imageReportTemplate.value.style.position;
      const originalTop = imageReportTemplate.value.style.top;
      const originalLeft = imageReportTemplate.value.style.left;

      // 临时设置为可见但在屏幕外
      imageReportTemplate.value.style.position = "fixed";
      imageReportTemplate.value.style.top = "-9999px";
      imageReportTemplate.value.style.left = "-9999px";
      imageReportTemplate.value.style.display = "block";

      // 强制重新布局
      imageReportTemplate.value.offsetHeight;

      const canvas = await html2canvas(imageReportTemplate.value, {
        backgroundColor: "#ffffff",
        scale: 1.5, // 降低缩放比例，避免内存问题
        useCORS: true,
        allowTaint: false,
        foreignObjectRendering: false,
        removeContainer: false,
        logging: false,
        width: 800,
        onclone: (clonedDoc) => {
          // 确保克隆文档中的样式正确应用
          const clonedElement = clonedDoc.querySelector(
            ".image-report-template"
          ) as HTMLElement;
          if (clonedElement) {
            clonedElement.style.display = "block";
            clonedElement.style.position = "static";
            clonedElement.style.top = "auto";
            clonedElement.style.left = "auto";
          }
        },
      });

      // 恢复原始样式
      imageReportTemplate.value.style.display = originalDisplay;
      imageReportTemplate.value.style.position = originalPosition;
      imageReportTemplate.value.style.top = originalTop;
      imageReportTemplate.value.style.left = originalLeft;

      // 验证canvas是否有效
      if (canvas.width === 0 || canvas.height === 0) {
        throw new Error("生成的图片尺寸无效");
      }

      // 生成图片数据
      const imageData = canvas.toDataURL("image/png", 1.0);

      // 验证图片数据
      if (!imageData || imageData === "data:,") {
        throw new Error("图片数据生成失败");
      }

      // 创建下载链接
      const link = document.createElement("a");
      const currentDate = new Date();
      const dateStr = `${currentDate.getFullYear()}-${(
        currentDate.getMonth() + 1
      )
        .toString()
        .padStart(2, "0")}-${currentDate
        .getDate()
        .toString()
        .padStart(2, "0")}`;
      link.download = `AI分析报告_${row.id.slice(-8)}_${dateStr}.png`;
      link.href = imageData;

      // 下载图片
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);

      ElMessage.success("图片报告下载成功！");

      // 记录成功信息
      console.log("图片生成成功:", {
        width: canvas.width,
        height: canvas.height,
        dataSize: imageData.length,
      });
    } else {
      throw new Error("报告模板元素未找到");
    }
  } catch (error: any) {
    console.error("生成图片报告失败:", error);
    ElMessage.error(`生成图片报告失败: ${error?.message || "未知错误"}`);

    // 如果图片生成失败，提供文本版本备选方案
    if (confirm("图片生成失败，是否下载文本版本报告？")) {
      downloadTextReport(row);
    }
  } finally {
    // 清理数据
    reportData.value = null;
  }
};

// 等待图片加载完成
const waitForImages = (): Promise<void> => {
  return new Promise((resolve) => {
    if (!imageReportTemplate.value) {
      resolve();
      return;
    }

    const images = imageReportTemplate.value.querySelectorAll("img");
    if (images.length === 0) {
      resolve();
      return;
    }

    let loadedCount = 0;
    const totalImages = images.length;

    const checkComplete = () => {
      loadedCount++;
      if (loadedCount === totalImages) {
        setTimeout(resolve, 100); // 额外等待100ms确保渲染完成
      }
    };

    images.forEach((img) => {
      if (img.complete) {
        checkComplete();
      } else {
        img.onload = checkComplete;
        img.onerror = checkComplete; // 即使加载失败也继续
      }
    });
  });
};

// 获取得分等级
const getScoreLevel = (score: number): string => {
  if (score >= 90) return "优秀";
  if (score >= 80) return "良好";
  if (score >= 70) return "中等";
  if (score >= 60) return "偏低";
  return "较低";
};

// 格式化分析文本（用于图片）
const formatAnalysisForImage = (text: string | undefined): string => {
  if (!text) return "";

  return (
    text
      // 移除HTML标签，保留纯文本
      .replace(/<[^>]*>/g, "")
      // 处理换行
      .split("\n")
      .map((line) => line.trim())
      .filter((line) => line)
      .map((line) => `<p style="margin: 8px 0; text-indent: 2em;">${line}</p>`)
      .join("")
  );
};

// 处理图片URL，确保能够正确加载
const getProxiedImageUrl = (imageUrl: string): string => {
  if (!imageUrl) return "";

  // 如果是完整的HTTP URL，直接返回
  if (imageUrl.startsWith("http://") || imageUrl.startsWith("https://")) {
    return imageUrl;
  }

  // 如果是相对路径，转换为绝对路径
  const baseUrl = "http://localhost:3000";
  return imageUrl.startsWith("/")
    ? `${baseUrl}${imageUrl}`
    : `${baseUrl}/${imageUrl}`;
};

// 处理图片加载错误
const handleImageError = (event: Event) => {
  const img = event.target as HTMLImageElement;
  console.warn("图片加载失败:", img.src);
  // 可以设置默认头像或占位符
  img.style.display = "none";
};

// 统一的下载报告处理
const handleDownloadReport = async (command: string, row: AiAnalysis) => {
  switch (command) {
    case "image":
      await handleDownloadImage(row);
      break;
    case "text":
      downloadTextReport(row);
      break;
    case "simple-image":
      await downloadSimpleImageReport(row);
      break;
    default:
      ElMessage.warning("未知的下载类型");
  }
};

// 简化版图片报告（备用方案）
const downloadSimpleImageReport = async (row: AiAnalysis) => {
  try {
    ElMessage.info("正在生成简化图片报告，请稍候...");

    // 创建一个简单的canvas
    const canvas = document.createElement("canvas");
    const ctx = canvas.getContext("2d");

    if (!ctx) {
      throw new Error("无法创建Canvas上下文");
    }

    // 设置画布尺寸
    canvas.width = 600;
    canvas.height = 800;

    // 填充白色背景
    ctx.fillStyle = "#ffffff";
    ctx.fillRect(0, 0, canvas.width, canvas.height);

    // 设置字体和样式
    ctx.fillStyle = "#333333";
    ctx.font = "24px Microsoft YaHei, sans-serif";
    ctx.textAlign = "center";

    let y = 50;
    const lineHeight = 35;

    // 绘制标题
    ctx.fillStyle = "#409EFF";
    ctx.font = "bold 32px Microsoft YaHei, sans-serif";
    ctx.fillText("AI面部分析报告", canvas.width / 2, y);
    y += lineHeight * 2;

    // 绘制分析编号
    ctx.fillStyle = "#666666";
    ctx.font = "16px Microsoft YaHei, sans-serif";
    ctx.fillText(`分析编号: ${row.id.slice(-8)}`, canvas.width / 2, y);
    y += lineHeight * 2;

    // 绘制基本信息
    ctx.fillStyle = "#333333";
    ctx.font = "20px Microsoft YaHei, sans-serif";
    ctx.textAlign = "left";
    const leftMargin = 50;

    ctx.fillText(`性别: ${row.gender}`, leftMargin, y);
    y += lineHeight;

    ctx.fillText(`年龄: ${row.age}岁`, leftMargin, y);
    y += lineHeight;

    ctx.fillText(`脸型: ${row.faceShape}`, leftMargin, y);
    y += lineHeight;

    ctx.fillText(`主要表情: ${row.mainEmotion}`, leftMargin, y);
    y += lineHeight;

    ctx.fillText(`检测人脸数: ${row.faceCount}个`, leftMargin, y);
    y += lineHeight * 2;

    // 绘制得分
    ctx.font = "bold 28px Microsoft YaHei, sans-serif";
    ctx.fillStyle = "#409EFF";
    ctx.textAlign = "center";
    ctx.fillText(`黄金比例得分: ${row.goldenRatioScore}%`, canvas.width / 2, y);
    y += lineHeight;

    ctx.font = "18px Microsoft YaHei, sans-serif";
    ctx.fillStyle = "#666666";
    ctx.fillText(
      `评级: ${getScoreLevel(row.goldenRatioScore)}`,
      canvas.width / 2,
      y
    );
    y += lineHeight * 2;

    // 绘制时间信息
    ctx.font = "14px Microsoft YaHei, sans-serif";
    ctx.fillStyle = "#999999";
    ctx.fillText(`分析时间: ${row.analysisTime}`, canvas.width / 2, y);
    y += lineHeight;
    ctx.fillText(
      `生成时间: ${new Date().toLocaleString()}`,
      canvas.width / 2,
      y
    );

    // 绘制底部信息
    y = canvas.height - 30;
    ctx.fillText("报告由AI智能分析系统生成 | 仅供参考", canvas.width / 2, y);

    // 下载图片
    const imageData = canvas.toDataURL("image/png", 1.0);
    const link = document.createElement("a");
    const currentDate = new Date();
    const dateStr = `${currentDate.getFullYear()}-${(currentDate.getMonth() + 1)
      .toString()
      .padStart(2, "0")}-${currentDate.getDate().toString().padStart(2, "0")}`;
    link.download = `AI简化报告_${row.id.slice(-8)}_${dateStr}.png`;
    link.href = imageData;
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);

    ElMessage.success("简化图片报告下载成功！");
  } catch (error) {
    console.error("生成简化图片报告失败:", error);
    ElMessage.error("生成简化图片报告失败，请尝试文本版本");
  }
};

// 文本版本报告下载（备用方案）
const downloadTextReport = (row: AiAnalysis) => {
  const reportContent = `
AI面部分析报告
=====================================

基本信息：
- 分析编号: ${row.id}
- 性别: ${row.gender}
- 年龄: ${row.age}岁
- 脸型: ${row.faceShape}
- 主要表情: ${row.mainEmotion}
- 检测人脸数: ${row.faceCount}个

分析结果：
- 黄金比例得分: ${row.goldenRatioScore}%
- 评级: ${getScoreLevel(row.goldenRatioScore)}
- 分析时间: ${row.analysisTime}

${
  row.aiAnalysis
    ? `
AI智能分析：
${row.aiAnalysis.replace(/<[^>]*>/g, "").trim()}
`
    : ""
}

=====================================
生成时间: ${new Date().toLocaleString()}
报告由AI智能分析系统生成 | 仅供参考
`;

  const blob = new Blob([reportContent], { type: "text/plain;charset=utf-8" });
  const url = window.URL.createObjectURL(blob);
  const link = document.createElement("a");
  const currentDate = new Date();
  const dateStr = `${currentDate.getFullYear()}-${(currentDate.getMonth() + 1)
    .toString()
    .padStart(2, "0")}-${currentDate.getDate().toString().padStart(2, "0")}`;
  link.download = `AI分析报告_${row.id.slice(-8)}_${dateStr}.txt`;
  link.href = url;
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);
  window.URL.revokeObjectURL(url);

  ElMessage.success("文本报告下载成功！");
};

// 兼容性：保留原有的下载方法（仅用于向后兼容）
// const handleDownload = (row: AiAnalysis) => handleDownloadCommand('with-images', row);

// Excel导出通用方法
const exportToExcel = async (
  data: AiAnalysis[],
  filename: string,
  includeImages = true
) => {
  try {
    if (includeImages) {
      // 如果需要包含图片，使用增强版导出
      await exportExcelWithImages(data, filename);
    } else {
      // 只导出路径的简单版本
      exportBasicExcel(data, filename);
    }
  } catch (error) {
    console.error("Excel导出失败:", error);
    // 如果图片导出失败，降级为基础导出
    if (includeImages) {
      console.log("图片导出失败，降级为路径导出...");
      exportBasicExcel(data, filename);
      ElMessage.warning("图片加载失败，已导出图片路径");
    } else {
      throw error;
    }
  }
};

// 基础Excel导出（只包含路径）
const exportBasicExcel = (data: AiAnalysis[], filename: string) => {
  // 构建表头
  const headers = excelColumns.map((col) => col.title);

  // 构建数据行
  const rows = data.map((row) => {
    return excelColumns.map((col) => {
      const value = row[col.key as keyof AiAnalysis];
      return col.formatter ? col.formatter(value, row) : value;
    });
  });

  // 合并表头和数据
  const sheetData = [headers, ...rows];

  // 创建工作表
  const worksheet = XLSX.utils.aoa_to_sheet(sheetData);

  // 设置列宽
  const colWidths = excelColumns.map((col) => ({
    wch: col.width || 15,
  }));
  worksheet["!cols"] = colWidths;

  // 创建工作簿
  const workbook = XLSX.utils.book_new();
  XLSX.utils.book_append_sheet(workbook, worksheet, "AI分析报告");

  // 导出文件
  XLSX.writeFile(workbook, `${filename}.xlsx`);
};

// 增强版Excel导出（包含嵌入图片）
const exportExcelWithImages = async (data: AiAnalysis[], filename: string) => {
  const ExcelJS = await import("exceljs");

  // 创建工作簿和工作表
  const workbook = new ExcelJS.Workbook();
  const worksheet = workbook.addWorksheet("AI分析报告");

  // 设置列定义
  const columns = excelColumns.map((col, index) => ({
    header: col.title,
    key: col.key,
    width: col.width || 15,
    style:
      index === 1
        ? {
            alignment: {
              horizontal: "center" as const,
              vertical: "middle" as const,
            },
          }
        : {},
  }));

  worksheet.columns = columns;

  // 设置表头样式
  const headerRow = worksheet.getRow(1);
  headerRow.font = { bold: true, size: 12 };
  headerRow.fill = {
    type: "pattern",
    pattern: "solid",
    fgColor: { argb: "FFE6F3FF" },
  };
  headerRow.alignment = { horizontal: "center", vertical: "middle" };

  // 处理数据行
  for (let i = 0; i < data.length; i++) {
    const row = data[i];
    const rowIndex = i + 2; // 从第2行开始（第1行是表头）

    // 添加数据行
    const excelRow = worksheet.addRow({
      id: row.id,
      imageUrl: "", // 图片列先留空，后面填充图片
      faceCount: row.faceCount,
      gender: row.gender,
      age: row.age,
      goldenRatioScore: `${row.goldenRatioScore}%`,
      mainEmotion: row.mainEmotion,
      faceShape: row.faceShape,
      analysisTime: row.analysisTime,
    });

    // 设置行高为适合图片的高度
    excelRow.height = 80;

    // 如果有图片URL，尝试加载并嵌入图片
    if (row.imageUrl) {
      try {
        const imageBuffer = await downloadImage(row.imageUrl);
        if (imageBuffer) {
          // 添加图片到工作簿
          const extension =
            (getImageExtension(row.imageUrl) as "png" | "jpeg" | "gif") ||
            "png";
          const imageId = workbook.addImage({
            buffer: imageBuffer,
            extension: extension,
          });

          // 将图片插入到对应的单元格
          worksheet.addImage(imageId, {
            tl: { col: 1, row: rowIndex - 1 }, // top-left位置 (B列，从0开始计数)
            ext: { width: 60, height: 60 }, // 图片尺寸
          });
        }
      } catch (error) {
        console.warn(`图片加载失败: ${row.imageUrl}`, error);
        // 如果图片加载失败，在单元格中显示路径
        worksheet.getCell(rowIndex, 2).value = row.imageUrl || "暂无图片";
      }
    } else {
      // 没有图片时显示提示
      worksheet.getCell(rowIndex, 2).value = "暂无图片";
    }

    // 设置数据行样式
    excelRow.alignment = { vertical: "middle" };
    if (i % 2 === 0) {
      excelRow.fill = {
        type: "pattern",
        pattern: "solid",
        fgColor: { argb: "FFF8F9FA" },
      };
    }
  }

  // 添加边框
  const borderStyle = {
    top: { style: "thin" as const },
    left: { style: "thin" as const },
    bottom: { style: "thin" as const },
    right: { style: "thin" as const },
  };

  worksheet.eachRow((row, _rowNumber) => {
    row.eachCell((cell) => {
      cell.border = borderStyle;
    });
  });

  // 生成Excel文件并下载
  const buffer = await workbook.xlsx.writeBuffer();
  const blob = new Blob([buffer], {
    type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
  });

  const url = window.URL.createObjectURL(blob);
  const link = document.createElement("a");
  link.href = url;
  link.download = `${filename}.xlsx`;
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);
  window.URL.revokeObjectURL(url);
};

// 下载图片的辅助函数
const downloadImage = async (imageUrl: string): Promise<ArrayBuffer | null> => {
  try {
    // 如果是相对路径，转换为绝对路径
    const fullUrl = imageUrl.startsWith("http")
      ? imageUrl
      : `http://localhost:3000${
          imageUrl.startsWith("/") ? "" : "/"
        }${imageUrl}`;

    const response = await fetch(fullUrl, {
      mode: "cors",
      credentials: "same-origin",
    });

    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }

    return await response.arrayBuffer();
  } catch (error) {
    console.error("下载图片失败:", error);
    return null;
  }
};

// 获取图片扩展名的辅助函数
const getImageExtension = (url: string): string | null => {
  if (!url) return null;
  const match = url.match(/\.(jpg|jpeg|png|gif|bmp|webp)$/i);
  return match ? match[1].toLowerCase() : null;
};

// 格式化分析文本 - 根据新的标题规则重新设计
const formatAnalysisText = (text: string | undefined) => {
  if (!text) return "";

  console.log("📝 原始AI分析文本:", text);

  let result = text
    // 1. 处理一级标题：独占一行的双星号标题 **标题**
    .replace(/^\*\*([^*]+)\*\*$/gm, '<h3 class="analysis-main-title">$1</h3>')

    // 2. 处理二级标题：序号 + 双星号标题，如 "1. **标题**"
    .replace(
      /^(\d+\.\s*)\*\*([^*]+)\*\*/gm,
      '<br><h4 class="analysis-sub-title">$2</h4>'
    )

    // 3. 处理普通段落：将换行转换为段落标签
    .split("\n")
    .map((line) => {
      const trimmed = line.trim();
      if (!trimmed) return "";

      // 如果已经是HTML标签，直接返回
      if (trimmed.includes("<h3") || trimmed.includes("<h4")) {
        return trimmed;
      }

      // 否则包装为普通段落
      return `<p class="analysis-paragraph">${trimmed}</p>`;
    })
    .filter((line) => line.trim())
    .join("");

  return result;
};

// 直接的表格滚动事件处理（备选方案）
const handleTableDirectScroll = (_event: any) => {
  // console.log('📜 表格直接滚动事件触发:', _event)

  if (loadingMore.value || !hasMoreData.value) {
    // console.log('⏳ 跳过滚动处理 - loadingMore:', loadingMore.value, 'hasMoreData:', hasMoreData.value)
    return;
  }

  // Element Plus 表格的滚动事件可能需要从不同的地方获取滚动容器
  nextTick(() => {
    if (!tableRef.value) return;

    // 尝试多种方式获取滚动容器
    const scrollContainer =
      tableRef.value.$el?.querySelector(".el-table__body-wrapper") ||
      tableRef.value.$el?.querySelector(".el-scrollbar__wrap") ||
      tableRef.value.$el?.querySelector(".el-table__body");

    if (scrollContainer) {
      const { scrollTop, scrollHeight, clientHeight } = scrollContainer;
      const distanceToBottom = scrollHeight - scrollTop - clientHeight;

      console.log(
        `📊 找到滚动容器，滚动信息: scrollTop=${scrollTop}, scrollHeight=${scrollHeight}, clientHeight=${clientHeight}, distanceToBottom=${distanceToBottom}`
      );

      // 检查是否滚动到底部（预留30px缓冲区）
      if (distanceToBottom <= 30) {
        console.log("🎯 触发加载更多数据");
        loadMoreData(true); // 滚动触底时显示加载提示
      }
    } else {
      console.warn("⚠️ 未找到有效的滚动容器");
    }
  });
};

// 设置表格滚动监听
const setupTableScrollListener = () => {
  // 清理之前的监听器
  if (scrollCleanup) {
    scrollCleanup();
    scrollCleanup = null;
  }

  nextTick(() => {
    console.log("🔧 开始设置表格滚动监听...");

    if (!tableRef.value) {
      console.warn("⚠️ tableRef.value 不存在");
      return;
    }

    console.log("📋 tableRef.value:", tableRef.value);

    // 获取表格体滚动容器
    const tableBodyWrapper = tableRef.value.$el?.querySelector(
      ".el-table__body-wrapper"
    );
    if (!tableBodyWrapper) {
      console.warn("⚠️ 找不到 .el-table__body-wrapper 元素");
      // 尝试其他可能的选择器
      const altSelector = tableRef.value.$el?.querySelector(
        ".el-scrollbar__wrap"
      );
      if (altSelector) {
        console.log("✅ 找到备用滚动容器 .el-scrollbar__wrap");
        setupScrollListener(altSelector);
      }
      return;
    }

    console.log("✅ 找到表格滚动容器:", tableBodyWrapper);
    setupScrollListener(tableBodyWrapper);
  });
};

// 设置 Intersection Observer 监听触底
const setupIntersectionObserver = () => {
  console.log("🔧 开始设置 Intersection Observer...");

  // 清理之前的观察器
  if (intersectionObserver) {
    intersectionObserver.disconnect();
    intersectionObserver = null;
  }

  if (!scrollTrigger.value) {
    console.warn("⚠️ scrollTrigger 元素不存在");
    return;
  }

  console.log("📍 scrollTrigger 元素:", scrollTrigger.value);
  console.log(
    "📊 当前状态 - hasMoreData:",
    hasMoreData.value,
    "loadingMore:",
    loadingMore.value
  );

  // 创建 Intersection Observer - 使用默认的视口作为根
  intersectionObserver = new IntersectionObserver(
    (entries) => {
      const entry = entries[0];
      console.log(
        "👁️ Intersection Observer 触发:",
        entry.isIntersecting,
        entry.intersectionRatio
      );

      if (entry.isIntersecting && !loadingMore.value && hasMoreData.value) {
        console.log("🎯 触发器进入视口，开始加载更多数据");
        loadMoreData(true); // 滚动触底时显示加载提示
      }
    },
    {
      root: null, // 使用默认视口作为根
      rootMargin: "50px", // 提前50px触发，确保能检测到
      threshold: 0, // 只要有一点点进入视口就触发
    }
  );

  // 开始观察触发器元素
  intersectionObserver.observe(scrollTrigger.value);
  console.log("✅ Intersection Observer 已设置");
};

// 设置滚动监听器的辅助函数
const setupScrollListener = (scrollContainer: HTMLElement) => {
  // 添加滚动事件监听
  const handleScroll = (event: Event) => {
    console.log("📜 触发滚动事件");

    if (loadingMore.value) {
      console.log("⏳ 正在加载中，跳过");
      return;
    }

    if (!hasMoreData.value) {
      console.log("🚫 没有更多数据，跳过");
      return;
    }

    const target = event.target as HTMLElement;
    if (!target) return;

    const { scrollTop, scrollHeight, clientHeight } = target;
    const distanceToBottom = scrollHeight - scrollTop - clientHeight;

    console.log(
      `📊 滚动信息: scrollTop=${scrollTop}, scrollHeight=${scrollHeight}, clientHeight=${clientHeight}, distanceToBottom=${distanceToBottom}`
    );

    // 检查是否滚动到底部（预留30px缓冲区）
    if (distanceToBottom <= 30) {
      console.log("🎯 触发加载更多数据");
      loadMoreData(true); // 滚动触底时显示加载提示
    }
  };

  scrollContainer.addEventListener("scroll", handleScroll);
  console.log("✅ 滚动事件监听器已绑定");

  // 设置清理函数
  scrollCleanup = () => {
    scrollContainer.removeEventListener("scroll", handleScroll);
    console.log("🧹 滚动事件监听器已清理");
  };
};

// 加载更多数据
const loadMoreData = async (showLoadingMessage = true) => {
  if (loadingMore.value || !hasMoreData.value) return;

  // 防抖处理：如果距离上次触发少于500毫秒，则忽略
  const now = Date.now();
  if (now - lastTriggerTime < 500) {
    console.log("⏰ 触发过于频繁，忽略此次请求");
    return;
  }
  lastTriggerTime = now;

  try {
    console.log("🚀 开始加载更多数据...");
    loadingMore.value = true;
    currentPage.value += 1;

    // 只在需要时显示加载中提示（滚动触底时，而非初始化时）
    if (showLoadingMessage) {
      loadingMessageInstance = ElMessage({
        message: "正在加载更多数据...",
        type: "info",
        duration: 0, // 设置为0表示不自动消失
        showClose: false,
      });
    }

    // 直接加载数据，不添加人为延迟
    await fetchData(true);

    // 关闭加载中提示
    if (loadingMessageInstance) {
      loadingMessageInstance.close();
      loadingMessageInstance = null;
    }

    if (!hasMoreData.value) {
      console.log("✅ 没有更多数据了");
      // 使用轻提示显示没有更多数据
      ElMessage({
        message: "没有更多了~",
        type: "info",
        duration: 2000,
        showClose: false,
      });
    } else {
      console.log("✅ 成功加载更多数据");
    }
  } catch (error) {
    console.error("❌ 加载更多数据失败:", error);

    // 关闭加载中提示
    if (loadingMessageInstance) {
      loadingMessageInstance.close();
      loadingMessageInstance = null;
    }

    ElMessage.error("加载更多数据失败");
    currentPage.value -= 1; // 回退页码
  } finally {
    loadingMore.value = false;
  }
};

// 获取统计数据
const fetchStatistics = async () => {
  try {
    console.log("📊 开始获取统计数据...");

    const response = await fetch("http://localhost:3000/aisave/statistics", {
      method: "GET",
      headers: {
        "Content-Type": "application/json",
      },
    });

    const result = await response.json();

    if (result.code === 200 && result.data) {
      console.log("✅ 统计数据获取成功:", result.data);

      // 更新统计数据
      Object.assign(statistics, {
        totalAnalysis: result.data.totalAnalysis || 0,
        todayAnalysis: result.data.todayAnalysis || 0,
        avgScore: result.data.avgScore || 0,
        successRate: result.data.successRate || 0,
      });

      console.log("📈 统计数据更新完成");
    } else {
      throw new Error(result.message || "获取统计数据失败");
    }
  } catch (error) {
    console.error("❌ 获取统计数据失败:", error);
    ElMessage.error("获取统计数据失败");

    // 使用默认数据
    Object.assign(statistics, {
      totalAnalysis: 0,
      todayAnalysis: 0,
      avgScore: 0,
      successRate: 0,
    });
  }
};

// 获取数据
const fetchData = async (isLoadMore = false) => {
  try {
    if (!isLoadMore) {
      loading.value = true;
    }
    console.log("📥 开始获取AI分析数据...");

    // 构建查询参数
    const params = new URLSearchParams();
    params.append("page", currentPage.value.toString());
    params.append("limit", pageSize.value.toString());

    // 添加搜索条件
    if (searchForm.gender) {
      params.append("gender", searchForm.gender);
    }

    if (searchForm.ageRange) {
      params.append("ageRange", searchForm.ageRange);
    }

    if (searchForm.dateRange && searchForm.dateRange.length === 2) {
      params.append("startDate", searchForm.dateRange[0]);
      params.append("endDate", searchForm.dateRange[1]);
    }

    const response = await fetch(
      `http://localhost:3000/aisave/list?${params}`,
      {
        method: "GET",
        headers: {
          "Content-Type": "application/json",
        },
      }
    );

    const result = await response.json();

    if (result.code === 200 && result.data) {
      console.log("✅ AI分析数据获取成功:", result.data);

      const newData = result.data.list || [];

      if (isLoadMore) {
        // 追加数据
        tableData.value = [...tableData.value, ...newData];
      } else {
        // 替换数据
        tableData.value = newData;
      }

      // 更新分页信息
      totalCount.value = result.data.total || 0;
      hasMoreData.value = tableData.value.length < totalCount.value;

      console.log(
        `📊 共加载 ${tableData.value.length} 条记录，总计 ${totalCount.value} 条`
      );
    } else {
      throw new Error(result.message || "获取数据失败");
    }
  } catch (error) {
    console.error("❌ 获取AI分析数据失败:", error);
    ElMessage.error("获取数据失败");

    if (!isLoadMore) {
      // 清空数据
      tableData.value = [];
    }
  } finally {
    if (!isLoadMore) {
      loading.value = false;
    }
  }
};

// 生命周期
onMounted(() => {
  fetchData().then(() => {
    // 数据加载完成后设置滚动监听
    setTimeout(() => {
      calculateTableHeight();
      setupTableScrollListener(); // 保留滚动监听作为备选
      setupIntersectionObserver(); // 主要使用 Intersection Observer
    }, 200); // 增加延迟确保表格完全渲染
  });
  fetchStatistics();

  window.addEventListener("resize", handleResize);
});

onUnmounted(() => {
  window.removeEventListener("resize", handleResize);
  // 清理滚动监听器
  if (scrollCleanup) {
    scrollCleanup();
  }
  // 清理 Intersection Observer
  if (intersectionObserver) {
    intersectionObserver.disconnect();
  }
  // 清理加载提示
  if (loadingMessageInstance) {
    loadingMessageInstance.close();
  }
});
</script>

